package com.eightywork.life.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import cn.jpush.android.api.JPushInterface;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.weibo.TencentWeibo;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.eightywork.life.R;
import com.eightywork.life.adapter.LoginNeighborAdapter;
import com.eightywork.life.model.Space;
import com.eightywork.life.model.Xiaoqu;
import com.eightywork.life.service.CacheService;
import com.eightywork.life.service.CpService;
import com.eightywork.life.service.DataService;
import com.eightywork.life.service.DoService;
import com.eightywork.life.service.SpaceService;
import com.eightywork.life.util.MyHttpException;
import com.eightywork.life.widget.RTPullListView;
import com.eightywork.life.widget.RTPullListView.OnRefreshListener;
import com.umeng.analytics.MobclickAgent;

public class LoginMapActivity extends BaseActivity implements OnClickListener,
		AMapLocationListener, LocationSource {
	private ImageButton leftButton, signinButton, registerButton;
	private AMap aMap;
	private OnLocationChangedListener mListener;
	private LocationManagerProxy mAMapLocationManager = null;
	private boolean isGotLocation;
	private LoginNeighborAdapter adapter;
	private List<Xiaoqu> list = new ArrayList<Xiaoqu>();
	private RTPullListView listView;
	private EditText search;
	private AMapLocation myLocation;
	private AsyncTask task, reg;
	private String username, seccode, password;
	private MapView mapView;
	private View listProgress;
	private ViewGroup footView;
	public static LoginMapActivity activity = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login_map);
		initData();
		initView(savedInstanceState);
		activity = this;
	}
	
	@Override
	public void onResume() {		
		super.onResume();
		JPushInterface.onResume(this);
	    MobclickAgent.onResume(this);
	}
	
	@Override
	public void onPause() {
	    super.onPause();
		JPushInterface.onPause(this);
	    MobclickAgent.onPause(this);
	}

	private void initData() {
		username = getIntent().getStringExtra("username");
		seccode = getIntent().getStringExtra("seccode");
		password = getIntent().getStringExtra("password");
		// username = "13480233393";
		// seccode = "123456";
		// password = "123456";
	}

	private boolean isReg() {
		return (username != null && seccode != null && password != null);
	}

	private void initView(Bundle savedInstanceState) {
		leftButton = (ImageButton) findViewById(R.id.button_left);
		leftButton.setOnClickListener(this);
		signinButton = (ImageButton) findViewById(R.id.sigin_button);
		signinButton.setOnClickListener(this);
		registerButton = (ImageButton) findViewById(R.id.register_button);
		registerButton.setOnClickListener(this);
		mapView = (MapView) findViewById(R.id.map);
		mapView.onCreate(savedInstanceState);
		aMap = mapView.getMap();
		aMap.getUiSettings().setMyLocationButtonEnabled(true);
		aMap.setLocationSource(this);
		aMap.setMyLocationEnabled(true);
		listView = (RTPullListView) findViewById(R.id.listView1);
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long id) {
				if(IndexActivity.activity != null) {
					IndexActivity.activity.finish();
				}
				String xiaoquid = list.get(position - 1).getXiaoquid();
				String xiaoquname = list.get(position - 1).getXiaoquname();
				String picUrl = list.get(position - 1).getPic_url();
				if (isReg()) {
					reg = new RegTask().execute(xiaoquid, xiaoquname);
				} else {
					Intent intent = new Intent(context, IndexActivity.class);
					intent.putExtra("xiaoquid", xiaoquid);
					intent.putExtra("xiaoquname", xiaoquname);
					intent.putExtra("picUrl", picUrl);				
					startActivity(intent);
					finish();
				}
			}
		});
		adapter = new LoginNeighborAdapter(context, list);
		footView = (ViewGroup) getLayoutInflater().inflate(
				R.layout.item_footer, null);
		listView.addFooterView(footView);
		listView.setAdapter(adapter);
		listView.setonRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				task = new ListTask().execute("local");
			}
		});
		search = (EditText) findViewById(R.id.search);
//		search.setOnEditorActionListener(new OnEditorActionListener() {
//			@Override
//			public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
//				mapView.setVisibility(View.GONE);
//				if (task != null)
//					task.cancel(true);
//				task = new ListTask().execute("search");
//				return false;
//			}
//		});
		search.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if(search.getEditableText().toString().equals("")){
					mapView.setVisibility(View.VISIBLE);
				}
				return false;
			}
		});
		search.addTextChangedListener(mTextWatcher);
		View footer = findViewById(R.id.footer);
		if (isReg()) {
			footer.setVisibility(View.GONE);
			leftButton.setImageResource(R.drawable.r18_c1);
		} else {
			footer.setVisibility(View.VISIBLE);
		}
		
	}
	
	TextWatcher mTextWatcher = new TextWatcher() {
		 private CharSequence temp;

		@Override
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub
			mapView.setVisibility(View.GONE);
			if (task != null)
				task.cancel(true);
			task = new ListTask().execute("search");
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			mapView.setVisibility(View.VISIBLE);
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub
			
			
		}
	
	};

	@Override
	public void onClick(View v) {
		if (v == registerButton) {
			Intent intent = new Intent(context, RegFirstActivity.class);
			startActivity(intent);
		} else if (v == signinButton) {
			Intent intent = new Intent(context, LoginActivity.class);
			startActivity(intent);
		} else if (v == leftButton) {
			Intent intent = new Intent(context, GuideActivity.class);
			startActivity(intent);
		}
	}

	@Override
	public void onDestroy() {
		deactivate();
		if (task != null)
			task.cancel(true);
		if (reg != null)
			reg.cancel(true);
		super.onDestroy();
	}


	@Override
	public void onLocationChanged(Location location) {
	}

	@Override
	public void onProviderDisabled(String provider) {

	}

	@Override
	public void onProviderEnabled(String provider) {

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {

	}

	/**
	 * 定位成功后回调函数
	 */
	@Override
	public void onLocationChanged(AMapLocation aLocation) {
		if (mListener != null) {
			mListener.onLocationChanged(aLocation);
			this.myLocation = aLocation;
			if (!isGotLocation) {
				task = new ListTask().execute("local");
				isGotLocation = true;
			}
		}
	}

	/**
	 * 激活定位
	 */
	@Override
	public void activate(OnLocationChangedListener listener) {
		mListener = listener;
		if (mAMapLocationManager == null) {
			mAMapLocationManager = LocationManagerProxy.getInstance(this);
		}
		mAMapLocationManager.requestLocationUpdates(
				LocationProviderProxy.AMapNetwork, 5000, 15, this);
	}

	/**
	 * 停止定位
	 */
	@Override
	public void deactivate() {
		mListener = null;
		if (mAMapLocationManager != null) {
			mAMapLocationManager.removeUpdates(this);
			mAMapLocationManager.destory();
		}
		mAMapLocationManager = null;
	}

	class ListTask extends AsyncTask<String, Void, String> {
		List<Xiaoqu> addList = new ArrayList();
		@Override
		protected void onPreExecute() {
//			listView.addFooterView(footView);
			super.onPreExecute();
		}
		
		@Override
		protected String doInBackground(String... params) {
			try {
				if (params[0].equals("search")) {
					addList = DoService.xiaoquSearch(search.getEditableText()
							.toString());
				} else {
					//System.out.println("---getLongitude--->" + myLocation.getLongitude() + ", " + myLocation.getLatitude());
					addList = DoService.xiaoquList("",
							myLocation.getLongitude() + "",
							myLocation.getLatitude() + "", "0.03");
				}
			} catch (MyHttpException e) {
				return e.getErrorMessage();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			listView.removeFooterView(footView);
			listView.onRefreshComplete();
			if (result == null) {
				list.clear();
				list.addAll(addList);
				for (int i = 0; i < list.size(); i++) {
					Xiaoqu item = list.get(i);
					LatLng potion = new LatLng(Double.valueOf(item
							.getLatitude()),
							Double.valueOf(item.getLongitude()));
					MarkerOptions marker = new MarkerOptions()
							.position(potion)
							.title(String.valueOf(i))
							.icon(BitmapDescriptorFactory
									.defaultMarker(BitmapDescriptorFactory.HUE_RED))
							.draggable(true);
					aMap.addMarker(marker);
				}
				Double geoLat = myLocation.getLatitude();
				Double geoLng = myLocation.getLongitude();
				aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
						new LatLng(geoLat, geoLng), 15));
				adapter.notifyDataSetChanged();
				
			} else {
				showMessage(result);
			}
			super.onPostExecute(result);
		}
	}

	class RegTask extends AsyncTask<String, String, String> {
		@Override
		protected void onPreExecute() {
			showProgressDialog("请稍后...");
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			try {
				String sina_uid = "";
				String sina_token = "";
				String sina_expires_in = "";
				String qq_openid = "";
				String qq_token = "";
				Platform weibo = ShareSDK.getPlatform(context, SinaWeibo.NAME);
				if (weibo.isValid()) {
					sina_uid = weibo.getDb().getUserId();
					sina_token = weibo.getDb().getToken();
					SimpleDateFormat sdf = new SimpleDateFormat(
							"yyyy-MM-dd HH:mm:ss");
					sina_expires_in = sdf.format(new Date(weibo.getDb()
							.getExpiresTime()));
				}
				Platform tweibo = ShareSDK.getPlatform(context,
						TencentWeibo.NAME);
				if (tweibo.isValid()) {
					qq_openid = tweibo.getDb().getUserId();
					qq_token = tweibo.getDb().getToken();
				}
				Space space = DoService.register(username, username, password,
						seccode, params[0], sina_uid, sina_token,
						sina_expires_in, qq_openid, qq_token);
//				System.out.println("========================" + space.getUid());
				space.setXiaoquid(params[0]);
				space.setXiaoquname(params[1]);
				CacheService.save(space);
				CacheService.saveProfile(CpService.profile());
				DataService.setGroupList(SpaceService.group());
				if (!DataService.isHavingTag()) {
					DataService.setTagList(SpaceService.tagList());
				}
			} catch (MyHttpException e) {
				return e.getErrorMessage();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			hideProgressDialog();
			if (result == null) {
				Intent intent = new Intent(context, FriendChooseActvity.class);
				startActivity(intent);
				finish();
				RegFirstActivity.activity.finish();
				RegSecondActivity.activity.finish();
			} else {
				showMessage(result);
			}
			super.onPostExecute(result);
		}
	}
}
